package com.turing.common.util;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.context.properties.ConfigurationProperties;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * JWT工具类
 */
@ConfigurationProperties("jwt.config")
public class JwtUtil {

    private String key;

    private long ttl;//一个小时

    private static JwtUtil jwtUtil;

    public static JwtUtil getJwtUtil() {
        return jwtUtil;
    }

    public static void setJwtUtil(JwtUtil jwtUtil) {
        JwtUtil.jwtUtil = jwtUtil;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成JWT
     *
     * @param userId   userId
     * @param account account
     * @param userName 用户名称
     * @param roles    角色
     * @param roleName 角色名称
     * @return java.lang.String
     * @author lcy
     * @date 2021/6/7 17:47
     **/
    public String createJWT(String userId, String account, String userName, String roles, String roleName) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(userId)
                .claim("userCode", account)
                .setSubject(userName)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("roles", roles)
                .claim("rolename", roleName);

        if (ttl > 0) {
            builder.setExpiration(new Date(nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 生成场景权限的JWT
     *
     * @param userId        userId
     * @param userCode      userCode,这里使用userEmail
     * @param userName      用户名称
     * @param roleIds         角色
     * @param roleNames      角色名称
     * @param templates 场景权限集合
     * @return java.lang.String
     * @author lcy
     * @date 2021/6/7 17:47
     **/
    public String createJWT(Integer userId, String userCode, String userName, Integer mainRoleId, String mainRoleName,
                            String roleIds, String roleNames, List<Integer> roleUserIds, List<Integer> menuList,
                            Map<String,Integer> templates, Map<String, Set<Integer>> elements,Set<String> compareTemplates,
                            Set<String> ocrTemplates,Map<String,List<Integer>> dataPrivilege) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(userId.toString())
                .claim("userCode", userCode)
                .setSubject(userName)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("mainRoleId", mainRoleId)
                .claim("mainRoleName", mainRoleName)
                .claim("roles", roleIds)
                .claim("roleNames", roleNames)
                .claim("roleUserIds", roleUserIds)
                .claim("menuList", menuList)
                .claim("templates", templates)
                .claim("elements", elements)
                .claim("compareTemplates",compareTemplates)
                .claim("ocrTemplates",ocrTemplates)
                .claim("dataPrivilege",dataPrivilege);

        if (ttl > 0) {
            builder.setExpiration(new Date(nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     *
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr) {
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

    public Integer getUserIdByToken(String token) {
        Claims claims = Jwts
                .parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
        try {
            return Integer.valueOf(claims.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JwtUtil getInstance() {
        if (jwtUtil == null) {
            synchronized (JwtUtil.class) {
                if (jwtUtil == null) {
                    jwtUtil = new JwtUtil();
                }
            }
        }
        return jwtUtil;
    }

    public static void main(String[] args) {

        String token  ="{\"jti\":\"34\",\"userCode\":\"test001\",\"sub\":\"????\",\"iat\":1649822094,\"mainRoleId\":2,\"mainRoleName\":\"????\",\"roles\":\"[2]\",\"roleNames\":\"[????]\",\"menuList\":[],\"templateList\":[\"66\",\"34\",\"46\",\"10\"],\"exp\":1650426894}";
        JSONObject jsonObject = JSONObject.parseObject(token);
        System.out.println(jsonObject);

    }

}
